package vinh.game;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/**
 *	Specific View 
 **/
public abstract class PersonalizedView extends LinearLayout{

	/**
	 * member variables
	 */
	private Context mContext;
	
	private Timer mUpdateTimer;
	
	private long mPeriod = 1000;
	
	/**
	 * Constructor
	 * @param context
	 */
	public PersonalizedView(Context context) {
		super(context);
		mContext = context;
	}
	
	/**
	 * Constructor overload
	 * @param context
	 * @param attrs
	 */
	public PersonalizedView(Context context, AttributeSet attrs){
		super(context,attrs);
		mContext = context;
	}
	
	/**
	 * Android specific view method
	 */
	protected void onLayout (boolean changed, int l, int t, int r, int b){
		super.onLayout(changed, l, t, r, b);
		try{
			initialize();
			startUpdateTimer();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Timer methods
	 */
	protected void setUpdatePeriod(long period){
		mPeriod = period;
	}
	/**
	 * inner class for timer task to be triggered by timer
	 */
	private class UpdateTask extends TimerTask{
		@Override
		public void run() {
			updatePhysics();
			postInvalidate();
		}
	
	}
	
	protected void startUpdateTimer(){
		mUpdateTimer = new Timer();
		mUpdateTimer.schedule(new UpdateTask(), 0, mPeriod);
	}
	
	protected void stopUpdateTimer(){
		if (mUpdateTimer != null){
			mUpdateTimer.cancel();
		}
	}
	
	/**
	 * getters for context, image 
	 **/
	public Context getContex(){
		return mContext;
	}
	
	protected Bitmap getImage(int id){
		return BitmapFactory.decodeResource(mContext.getResources(), id);
	}

	/**
	 * abstract methods Game has got to implement
	 */
	abstract protected void updatePhysics();
	
	abstract protected void initialize();
	
	abstract protected void kill();
	

	
	/**
	 * methods for android behavior
	 */
	public void halt(){
		stopUpdateTimer();
		kill();
	}
	
	public void resume(){
		initialize();
		startUpdateTimer();
	}

}
